package org.csu.code.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.csu.code.api.common.CommonResponse;
import org.csu.code.api.entity.Cart;
import org.csu.code.api.entity.Item;
import org.csu.code.api.entity.Product;
import org.csu.code.api.persistence.CartMapper;
import org.csu.code.api.persistence.ItemMapper;
import org.csu.code.api.persistence.ProductMapper;
import org.csu.code.api.service.CartService;
import org.csu.code.api.vo.CartItemVO;
import org.csu.code.api.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service("cartService")
public class CartServiceImpl implements CartService {

    @Autowired
    CartMapper cartMapper;
    @Autowired
    CartVO cartVO;
    @Autowired
    ItemMapper itemMapper;
    @Autowired
    ProductMapper productMapper;
    @Autowired
    Cart cart;
    @Autowired
    CartService cartService;


    @Override
    //查询用户的购物车
    public CommonResponse<List<CartItemVO>> getCartItemByUserid(int userid) {
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<Cart>();
        cartQueryWrapper.eq("userid",userid);
        List<Cart> cartList = cartMapper.selectList(cartQueryWrapper);
        System.out.println(cartList.size());
        if (cartList.isEmpty()){
            return CommonResponse.createForSuccessMessage("购物车为空");
        }
        List<CartItemVO> cartItemVOList = new ArrayList<>();
        for (int i = 0;i<cartList.size();i++){
            //cart中的属性
            Cart cart = cartList.get(i);
            System.out.println(cart.toString());
            CartItemVO cartItemVO = new CartItemVO();
            cartItemVO.setUserid(cartList.get(i).getUserid());
            cartItemVO.setItemid(cartList.get(i).getItemid());
            cartItemVO.setDescription(cartList.get(i).getDescription());
            cartItemVO.setInstock(cartList.get(i).getInStock());
            cartItemVO.setQuantity(cartList.get(i).getQuantity());
            cartItemVO.setListprice(cartList.get(i).getListPrice());
            cartItemVO.setTotalprice(cartList.get(i).getTotalPrice());
            //item中的属性
            //查出对应itemid的item
            Item item = itemMapper.selectById(cartList.get(i).getItemid());
            cartItemVO.setSupplierId(item.getSupplierId());
            cartItemVO.setStatus(item.getStatus());
            cartItemVO.setItemName(item.getName());
            cartItemVO.setAttribute1(item.getAttribute1());
            cartItemVO.setAttribute2(item.getAttribute2());
            cartItemVO.setAttribute3(item.getAttribute3());
            //product中的属性
            //查出对应productid的product
            Product product = productMapper.selectById(item.getProductId());
            cartItemVO.setCategoryId(product.getCategoryId());
            cartItemVO.setName(product.getName());
            cartItemVOList.add(cartItemVO);
            System.out.println(cartItemVOList);
        }
        return CommonResponse.createForSuccess(cartItemVOList);
    }


    @Override
    //添加商品进入购物车
    public CommonResponse<CartVO> addItem(int userid, int itemid, int quantity){
        Item item = itemMapper.selectById(itemid);
        Product product = productMapper.selectById(item.getProductId());
        //加入商品信息
        cart.setUserid(userid);
        cart.setItemid(itemid);
        cart.setDescription(item.getDescription());
        //判断是否有库存
        if(item.getStock() != 0)
            cart.setInStock(1);
        else
            cart.setInStock(0);
        cart.setQuantity(quantity);
        cart.setListPrice(item.getListPrice());
        //总价
        double totalprice = 0;
        //判断是否已经存在此用户的此商品
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.and(wrapper -> wrapper.eq("userid",cart.getUserid()).eq("itemid",cart.getItemid()));
        Cart cartresult = cartMapper.selectOne(cartQueryWrapper);
        if (cartresult == null){
            //不存在此商品,计算总价后插入
            System.out.println("不存在此商品");
//            totalprice = cartService.totalItemPrice(userid) + item.getListPrice().doubleValue()*quantity;
            totalprice = item.getListPrice().doubleValue()*quantity;
            //double转价格后插入
            cart.setTotalPrice(new BigDecimal(Double.toString(totalprice)));
            cartMapper.insert(cart);
        }else {
            //存在此商品，更新数据库中商品数量再计算总价
            System.out.println("存在此商品");
            cartresult.setQuantity(cartresult.getQuantity()+quantity);
            totalprice = cartresult.getListPrice().doubleValue()*cartresult.getQuantity();
            System.out.println("此商品当前数量"+cartresult.getQuantity());
            //计算总价再更新
//            totalprice = cartService.totalItemPrice(userid);
            cartresult.setTotalPrice(new BigDecimal(Double.toString(totalprice)));
            cartMapper.update(cartresult, cartQueryWrapper);
            System.out.println("商品总价为"+cartresult.getTotalPrice());
//            cartMapper.updateById(cartresult);
        }
        //返回结果
        cartQueryWrapper.and(wrapper -> wrapper.eq("userid",cart.getUserid()).eq("itemid",cart.getItemid()));
            return CommonResponse.createForSuccessMessage("加入购物车成功");

    }

    @Override
    //更新购物车
    public CommonResponse<BigDecimal> updateQuantity(int userid, int quantity,int itemId) {
        //从数据库中查找
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.and(wrapper -> wrapper.eq("userid",userid).eq("itemid",itemId));
        Cart cart = cartMapper.selectOne(cartQueryWrapper);
        if (cart == null){
            return CommonResponse.createForError("更新购物车失败");
        }
        //将cart中的数量修改
        cart.setQuantity(quantity);
        //将此结果更新到数据库
        cartMapper.updateById(cart);
        //计算总价再更新
        double totalprice = cartService.totalItemPrice(userid);
        cart.setTotalPrice(new BigDecimal(Double.toString(totalprice)));
        cartMapper.updateById(cart);
//        cart.setTotalPrice(cart.getListPrice().multiply(new BigDecimal(quantity)));
//        //重新获取cartlist
//        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("userid",userid);
//        List<Cart> cartList = cartMapper.selectList(queryWrapper);
//        if (cartList.isEmpty()){
//            return CommonResponse.createForSuccessMessage("购物车为空");
//        }
//        for (int i = 0;i<cartList.size();i++){
//            //修改总价并插入表
//            cartList.get(i).setTotalPrice(new BigDecimal(Double.toString(totalprice)));
//            cartMapper.updateById(cartList.get(i));
//        }
        if(cart.getQuantity() != quantity){
            return CommonResponse.createForError("更新购物车失败");
        }
        else {
            return CommonResponse.createForSuccess(cart.getTotalPrice());
        }

    }

    @Override
    public CommonResponse<Cart> deleteByUserid(int userid) {
        //清空购物车
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.eq("userid",userid);
        cartMapper.delete(cartQueryWrapper);
        return CommonResponse.createForSuccessMessage("清空成功");
    }

    @Override
    //删除购物车中商品
    public CommonResponse<CartVO> deleteCartitemByUserid(int userid,int itemid) {
        //删除指定item
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.and(wrapper -> wrapper.eq("userid",userid).eq("itemid",itemid));
        cartMapper.delete(cartQueryWrapper);
        return CommonResponse.createForSuccessMessage("删除购物车中商品成功");

    }

    @Override
    //计算某用户购物车总价
    public double totalItemPrice(int userid){
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.eq("userid",userid);
        List<Cart> cartList = cartMapper.selectList(cartQueryWrapper);
        //计算总价
        double totalprice = 0;
        for (int i = 0;i<cartList.size();i++){
            totalprice += cartList.get(i).getListPrice().doubleValue()*cartList.get(i).getQuantity();
        }
        return totalprice;
    }
}
